<?php
namespace Admin\Model;
use Think\Model;
class CustomerModel extends Model {
	const STATE_NEED_AUTH = 0; //待审核客户
	const STATE_NORMAL = 1;//正常客户
	const STATE_BAN_LOGIN = 2; //禁止登录的客户
	const STATE_COMBINE = 3; //被合并客户
	const STATE_INVALID_USER = 4; //无效客户

	//添加客户
	public function customerAdd($arr){
		//个人信息
		$uinfo = $this->User();

		$date = date("Y-m-d H-i-s");
		$map['login_name']       = $arr['customer_name'];
		$map['pass']             = md6($arr['customer_pass'].$arr['customer_name'].$date);
		$map['nickname']         = $arr['customer_name'];
		$map['phone']            = $arr['customer_phone'];
		$map['qq']               = $arr['customer_qq'];
		$map['weixin_id']        = $arr['customer_weixin_id'];
		$map['weixin_nickname']  = $arr['customer_weixin_nickname'];
		$map['mount']            = $arr['customer_mount'];
		$map['sex']              = $arr['sex'];
		$map['career']           = $arr['career'];
		$map['education']        = $arr['education'];
		$map['birthday']         = $arr['customer_birth'];
		$map['count_contact']    = 0;
		$map['source_id']        = $arr['sources'];
		$map['note']             = $arr['customer_note'];
		$map['location']         = $arr['customer_location'];
		$map['address']          = $arr['customer_address'];
		$map['is_delete']        = 0;
		$map['state']            = 1;
		$map['sales_person']     = $uinfo['user_id'];
		$map['sales_sector']     = $uinfo['sector_id'];
		$map['sales_role']       = $uinfo['role_id'];
		$map['sector_id']        = $uinfo['sector_id'];
		$map['create_time']      = date("Y-m-d H-i-s");
		$map['last_time']        = date("Y-m-d H-i-s");
		$map['last_ip']          = get_client_ip();;
		$map['stock_account_state'] = 0;
		$map['is_new']           = 1;
		//$map['protect_time']     =  date("Y-m-d",strtotime("+10 days"));
		$map['protect_time']	 =  date("Y-m-d",mktime(0,0,0,date("m"),date("d")+10,date("Y")));

		$map['develop_times']    = 1;
		$list = M("customer")->add($map);
		if($list)
			$res['rcode'] = 1;
		else
			$res['msg'] = "客户添加失败!";
		return $res;
	}
	//修改客户信息
	public function customerEditor($arr){
		$map['nickname']         = $arr['nickname'];
		$map['phone']            = $arr['phone'];
		$map['qq']               = $arr['qq'];
		$map['weixin_id']        = $arr['weixin_id'];
		$map['weixin_nickname']  = $arr['weixin_nickname'];
		$map['mount']            = $arr['mount'];
		$map['sex']              = $arr['sex'];
		$map['career']           = $arr['career'];
		$map['education']        = $arr['education'];
		$map['birthday']         = $arr['birth'];
		$map['source_id']        = $arr['sources'];
		$map['note']             = $arr['note'];
		$map['location']         = $arr['location'];
		$map['address']          = $arr['address'];
		$map['sector_id']        = $uinfo['sector_id'];
		$map['create_time']      = date("Y-m-d H-i-s");
		$map['protect_time']     =  date("Y-m-d",strtotime("+".$arr['protect_time']." days"));
		$where['customer_id'] = $arr['customer_id'];
		$list = M("customer")->where($where)->save($map);
		if($list)
			$res['rcode'] = 1;
		else
			$res['msg'] = "客户编辑失败!";
		return $res;
	}
	//客户转移加载
	public function transferShow($is_admin){
		$uinfo  = $this->User();
		$role   = M("role")->select();
		$list   = list_to_role($role,$uinfo['role_id']);
		$user   = M("user");
		$where['state']  = array('eq','-1');
		if($uinfo['user_id'] == 1){
			//超级管理员
			//离职人员
			$res['transfer']['absent'] = $user->field("user_id,nickname")->where($where)->select();
			//部门信息
			$map['parent_company'] = 1;
			$res['transfer']['arr']   = M("sector")->field("sector_id,sector_name,parent_company")->where($map)->select();
		}else{
			foreach ($list as $key => $value) {
				$where['role_id']  = $value['role_id'];
				$leave[$key] = $user->field("user_id,nickname")->where($where)->select();
			}
			//离职员工
			foreach ($leave as $val) {
				if(!empty($val)){
					foreach ($val as $keys => $v) {
						if(!empty($v)){
							$res['transfer']['absent'][] = $v;
						}
					}
				}
			}
			//下属部门
			$sector = M("sector")->select();
			$lists = list_to_sector($sector,$uinfo['sector_id']);
			foreach ($lists as $k => $values) {
				$maps['sector_id']   = $values['sector_id'];
				$array[$k][] = M("sector")->field("sector_id,sector_name")->where($maps)->select();
			}
			foreach ($array as $child) {
				if(!empty($child)){
					foreach ($child as $subset) {
						if(!empty($subset)){
							foreach ($subset as $lower) {
								if(!empty($lower)){
									$res['transfer']['arr'][] = $lower;
								}
							}
						}
					}
				}
			}
		}
		return $res;
	}
	//在职人员
	public function TeamPerson($sector_id){
		$uinfo = $this->User();

		$sector = M("sector")->select();
		$list = list_to_sector($sector,$sector_id);
		if($uinfo['user_id']=='1'){
			foreach ($list as $key => $value) {
				$wheres['sector_id'] = $value['sector_id'];
				$wheres['state'] = array('neq','-1');
				$service_person[] =  M("user")->field("user_id,nickname")->where($wheres)->select();
			}
			foreach ($service_person as $k => $v) {
				if(!empty($v)){
					foreach ($v as $ks => $values) {
						if(!empty($values)){
							$res['service_person'][] = $values;
						}
					}
				}
			}
		}else{
			foreach ($list as $key => $value) {
				$wheres['sector_id'] = $value['sector_id'];
				$wheres['state'] = array('neq','-1');
				$service_person[] =  M("user")->field("user_id,nickname")->where($wheres)->select();
			}
			foreach ($service_person as $k => $v) {
				if(!empty($v)){
					foreach ($v as $ks => $values) {
						if(!empty($values)){
							$res['service_person'][] = $values;
						}
					}
				}
			}
		}
		return $res;
	}
	//客户转移
	public function customerTransfer($array){
		//未转移前客户信息
		$where['sales_person'] = $array['leave'] ;
		//合同
		$list = M("contract")->where($where)->select();
		//客户
		$arr = M("customer")->where($where)->select();
		return $array;
		//续费
		$maps['user_id'] = $array['leave'];
		$xlist = M("customer_xufei")->where($maps)->select();
		//转移的服务人员信息
		$where['user_id'] = $array['attends'];
		$receiver = M("user")->field("user_id,sector_id,role_id,state")->where($where)->find();

		$user = M("user")->field("state")->where($maps)->find();
		if($user['state'] != "-1" ){
			$res['rcode'] = "该员工不属于离职状态，禁止转出相应客户!!！";
		}else{
			//信息转移
			$wheres['sales_person'] = ['user_id'];
			if(!empty($list)){
				foreach ($list as &$value) {

					$wheres['sales_sector'] = $receiver['sector_id'];
					$new_list = M("contract")->where($where)->save($wheres);
				}
			}
			if(!empty($arr)){
				foreach ($arr as &$val) {
					$wheres['sales_sector'] = $receiver['sector_id'];
					$wheres['sales_role'] = $receiver['role_id'];
					$new_arr = M("customer")->where($where)->save($wheres);
				}
			}
			if(!empty($xlist)){
				foreach ($xlist as &$vv) {
					$new_xlist = M("customer_xufei")->where($maps)->save($wheres);
				}
			}
			$res['rcode'] = "1";
		}
		return $res;
	}
	public function User (){
		$uinfo = UserModel::loadFromSession();
		return $uinfo;
	}

/*------------------------------------view360使用接口begin---------------------------------------------*/

	/*view360-编辑客户基本信息*/
	public function updateCustomer($edit_data){
        $r = array('d'=>NULL,'i'=>'','r'=>0);
        if( $edit_data['customer_id']) {
        	$wheres1 = array();
            $wheres1['customer_id'] = array('eq', $edit_data['customer_id'] );
            $wheres1['is_delete'] = array('neq', 1);
            $editCustomer = $this->where( $wheres1 )->find();
            if( $editCustomer ){
            	$d = array();
                $d['update_time'] = date('Y-m-d H:i:s');
                if($edit_data['editSenvInfo']){	//编辑客户敏感信息
                	$d['nickname'] = $edit_data['nickname'];
                	$d['phone'] = $edit_data['phone'];
                	$d['qq'] = $edit_data['qq'];
                	$d['weixin_id'] = $edit_data['weixin_id'];
                }
                if($edit_data['locationEdit'])  $d['location'] = $edit_data['location'];
                if($edit_data['sexEdit'] && $edit_data['sex'] != 3)   $d['sex'] = $edit_data['sex'];
                else if($edit_data['sexEdit'] && $edit_data['sex'] == 3)    $d['sex'] = 0;
                if($edit_data['mountEdit'])     $d['mount'] = $edit_data['mount'];
                if($edit_data['birthdayEdit'])      $d['birthday'] = $edit_data['birthday'];
                if($edit_data['careerEdit'])    $d['career'] = $edit_data['career'];
                if($edit_data['educationEdit'])     $d['education'] = $edit_data['education'];
                if($edit_data['addressEdit'])   $d['address'] = $edit_data['address'];
                if($edit_data['remarkEdit'])    $d['remark'] = $edit_data['remark'];
                if($edit_data['editSenvInfo'] && $d['phone']){
                	if(1 == $edit_data['storeOrNot']){	//phone保存到保存历史
                		$wheres2 = array();
	                    $wheres2['customer_id'] = array('eq',$edit_data['customer_id']);
	                    $wheres2['book_phone'] = array('eq',$d['phone']);
	                    $findPhone = M('customer_phonebook')->where($wheres2)->find();
	                    if($findPhone){
	                        //历史记录存在
	                        $delPhone = M('customer_phonebook')->where($wheres2)->delete();
	                    }
                        $phones = array();
                        $phones['book_phone'] = $edit_data['phone'];
                        $phones['customer_id'] = $edit_data['customer_id'];
                        $phones['is_main'] = 1;
                        $phones['in_use'] = 1;
                        $addPhone = M('customer_phonebook')->add($phones);
                        if(!$addPhone){
                            $r['i'] = 0;
                            $r['i'] = '客户电话记录添加失败！';
                            return $r;
                        }
                	}
                    //超过7位电话号码查询归属地赋值给客户所在地
                    if($d['phone'] && strlen($d['phone'])>=7){
                        $phone = substr($d['phone'], 0 ,7);
                        $maps = array();
                        $maps['codefield'] = array('eq',$phone);
                        $areaInfo = M("om_mobilecode")->where($maps)->find();
                        if($areaInfo && !$d['location'])
                            $d['location'] = $areaInfo['province'];
                    }
                }
                $editID = M("customer")->where( $wheres1 )->save( $d );
                if( $editID || $editID==0 ){
                    $r['r'] = 1;
                    $r['d'] = $editID;
                    $r['i'] = 'OK';
                }
            }else
                $r['i'] = '抱歉，数据不存在！';
        }else{
            $r['i'] = '参数错误！';
        }
        return $r;
    }

    /*view360-获取当前客户及其归并客户id*/
	public function getCustIdAll($customer_id){
		$map = array();
		$map['combine_to'] = array('eq',$customer_id);
		$combinFromInfo = M('Customer')->field('customer_id')->where($map)->select();
		$v = count($combinFromInfo)+1;
	    $combinFromInfo[$v]['customer_id'] = $customer_id;
	   	$combinFromInfo = array_reverse($combinFromInfo);
        foreach ($combinFromInfo as $ck => $cval) {
            $combinFromInfoD[] = intval($cval['customer_id']);
        }
	   	return($combinFromInfoD);
	}

    /**view360-添加沟通信息*/
    public function add_contact($customer_id,$content){
        $uinfo = UserModel::loadFromSession();
        $r =array('r'=>0,'d'=>NULL,'m'=>'OK');
        if(!$content){
            $r['m'] = '表单信息获取失败！';
        }else{
            $d = array();
            $d['customer_id'] = $customer_id;
            $d['sales_id'] = $uinfo['user_id'];
            $d['sales_sector'] = $uinfo['sector_id'];
            $d['content'] = $content;
            $d['create_time'] = date('Y-m-d H:i:s');
            $d['type'] = 1;
            $addID = M("customer_contact_log")->add($d);
            if( $addID ){
                $r['r'] = 1;
                $r['d'] =$addID;
            }else{
                $r['m'] = '沟通信息添加失败！';
            }
        }
        return $r;
    }
    
    /*view360-计算时间差*/
    public function diffBetweenTwoDays($day1, $day2){
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);
        return intval(($second1 - $second2) / 86400);
    }

    /*view360-获取付款信息*/
    public function getPayInfos($customer_id){
        //获取当前客户及其归并客户id
        $combinFromInfo = $this->getCustIdAll($customer_id);
        $wheres1 = array();
        $wheres1['pay_record.customer_id'] = array('in',$combinFromInfo);
        $wheres1['c.state'] = array('neq',2);
        $payInfo = M('pay_record')->field('pay_record.pay_mount,pay_record.pay_way,pay_record.pay_time,c.contract_id,c.order_num,
                            pay_record.pay_type,pay_record.sales_person,pay_record.audit_res as status,user.nickname,c.product_id,
                            pay_record.payrecord_id,pay_record.pay_name,pay_record.audit_msg,pay_record.remark,pay_record.pay_order')
                            ->join("LEFT JOIN user on user.user_id=pay_record.sales_person")
                            ->join("LEFT JOIN contract c on c.contract_id=pay_record.contract_id")
                            ->where($wheres1)
                            ->order("pay_record.pay_time desc,pay_record.payrecord_id")
                            ->select();            
        for ($j=0; $j < count($payInfo); $j++) {
            $wheres2[$j] = array();
            $wheres2[$j]['product_id'] = $payInfo[$j]['product_id'];
            $productName[$j] = M('product')->where($wheres2[$j])->getField('name');
            $payInfo[$j]['productName'] = $productName[$j];
            $payInfo[$j]['pay_time'] = date('Y-m-d',strtotime($payInfo[$j]['pay_time']));
            //去掉付款金额后面的'.00'
            if($payInfo[$j]['pay_mount'] && substr($payInfo[$j]['pay_mount'], -3) == '.00'){
                $payInfo[$j]['pay_mount'] = floor($payInfo[$j]['pay_mount']);
            }
        }
        return $payInfo;
    }

    /*获取合同信息*/
    public function getContractInfos($customer_id){
        $today = date('Y-m-d H:i:s');
        //获取当前客户及其归并客户id
        $combinFromInfo = $this->getCustIdAll($customer_id);
        $wheres1 = array();
        $wheres1['contract.customer_id'] = array('in',$combinFromInfo);
        $contractInfo = M('contract')
                    ->field('p.name as productName,contract.start_time,contract.end_time,u.nickname as sales_name,
                    contract.state,contract.contract_id,contract.order_num,contract.customer_id,contract.create_time')
                    ->join("LEFT JOIN user u on u.user_id=contract.sales_person")
                    ->join("LEFT JOIN product p on p.product_id=contract.product_id")
                    ->where($wheres1)
                    ->order("contract.create_time desc,contract.contract_id")
                    ->select();
        $servicedDay = 0;
        $servicedTimeAll = 0;
        $servicedTime = 0;
        $noservicedTime = 0;
        for ($j=0; $j < count($contractInfo); $j++) {
            $remainDays[$j] = $this->diffBetweenTwoDays($contractInfo[$j]['end_time'],$today);
            if($remainDays[$j] && $remainDays[$j]>0){
                $contractInfo[$j]['remainDays'] = $remainDays[$j];
            }
            //计算合同时长
            $contractInfo[$j]['contractDays'] = $this->diffBetweenTwoDays($contractInfo[$j]['end_time'],$contractInfo[$j]['start_time']);
            //计算累加服务时长：只统计进行中、到期合同
            if(1 == $contractInfo[$j]['state'] || 3 == $contractInfo[$j]['state']){
                $contractInfoNeed[$j] = $contractInfo[$j];
            }
            //计算合同付款金额
            $wheres2[$j] = array();
            $wheres2[$j]['contract_id'] = array('eq',$contractInfo[$j]['contract_id']);
            $payMount[$j] = M('pay_record')->field('sum(pay_mount) as paymount')->where($wheres2[$j])->find();
            $contractInfo[$j]['paymount'] = $payMount[$j]['paymount'];
            $contractInfo[$j]['start_time'] = date('Y-m-d',strtotime($contractInfo[$j]['start_time']));
            $contractInfo[$j]['end_time'] = date('Y-m-d',strtotime($contractInfo[$j]['end_time']));
            //去掉合同付款金额后面的'.00'
            if($contractInfo[$j]['paymount'] && substr($contractInfo[$j]['paymount'], -3) == '.00'){
                $contractInfo[$j]['paymount'] = floor($contractInfo[$j]['paymount']);
            }
        }
        foreach ($contractInfoNeed as $key => $row) {
            $start_time[$key]  = $row['start_time'];
        }
        array_multisort($start_time, SORT_ASC, $contractInfoNeed); //排序
        
        if($contractInfoNeed){
            $servicedTimeAll = (strtotime($today)-strtotime($contractInfoNeed[0]['start_time']));  //计算最早签订合同到现在时间差
            for ($m=0; $m < count($contractInfoNeed); $m++) {   //签订合同期间完成的合同，不计入统计中
                if($contractInfoNeed[$m]['start_time']>=$contractInfoNeed[$m-1]['start_time'] && $contractInfoNeed[$m]['end_time']<=$contractInfoNeed[$m-1]['end_time'])
                    unset($contractInfoNeed[$m]);
                $contractInfoNeed = array_values($contractInfoNeed);
            }
            for ($n=1; $n < count($contractInfoNeed); $n++) {   //两个合同间隔时间差
                if($contractInfoNeed[$n]['start_time']>$contractInfoNeed[$n-1]['end_time']){
                    $noservicedTime += (strtotime($contractInfoNeed[$n-1]['end_time'])-strtotime($contractInfoNeed[$n]['start_time']));
                }
            }
            $servicedTime = $servicedTimeAll+$noservicedTime;
        }
        $servicedDay = intval($servicedTime / (24*3600));
        return array($contractInfo,$servicedDay);
    }

/*------------------------------------view360使用接口end---------------------------------------------*/
}